package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;

/**
 * @author: 成金乘
 * @date: 2023/5/14 14:53
 * @description:
 */
@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    protected ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //尝试获取queryString.存在博客详情页,反之列表页
        BlogDao blogDao = new BlogDao();
        String blogId = req.getParameter("blogId");
        if(blogId == null){
            List<Blog> blogs = blogDao.selectAll();
            //把blogs转成符合json格式的字符串
            String respJson = objectMapper.writeValueAsString(blogs);
            resp.setContentType("application/json; charset=utf8");
            resp.getWriter().write(respJson);
        }else {
            Blog blog = blogDao.selectById(Integer.parseInt(blogId));
            if(blog == null){
                System.out.println("对应博客不存在");
            }
            String respJson = objectMapper.writeValueAsString(blog);
            resp.setContentType("application/json; charset=utf8");
            resp.getWriter().write(respJson);
        }
    }
    //发布博客

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if (session == null){
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户未登录,无法发布博客");
            return;
        }
        User user = (User)session.getAttribute("user");
        if (user == null){
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户未登录,无法发布博客");
            return;
        }
        req.setCharacterEncoding("utf8");
        //获取博客标题和正文
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        if(null == title || title.equals("") || null == content || content.equals("")){
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("标题或正文为空");
            return;
        }
        //构造Blog对象
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getUserId());
        blog.setPostTime(new Timestamp(System.currentTimeMillis()));
        //插入数据库
        BlogDao blogDao = new BlogDao();
        blogDao.add(blog);

        resp.sendRedirect("blog_list.html");
    }
}
